package com.xh.jf_blog.service.impl;

import com.xh.jf_blog.bean.ArticleTag;
import com.xh.jf_blog.bean.Tag;
import com.xh.jf_blog.common.exception.RTException;
import com.xh.jf_blog.mapper.ArticleTagMapper;
import com.xh.jf_blog.mapper.TagMapper;
import com.xh.jf_blog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author PangJunjie
 * @Date 2024/2/21/021
 */
@Service
@Transactional
public class TagServiceImpl implements TagService {
    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    public List<Tag> getListByUserinfoId(int userinfoId) {
        Tag tag = new Tag();
        tag.setUserinfoId(userinfoId);
        return tagMapper.getAll(tag);
    }

    public Tag getById(int tagId) {
        return tagMapper.selectByPrimaryKey(tagId);
    }

    public void saveOrUpdate(Tag tag) {
        if (tag.getTagId() == null) {
            tagMapper.insertSelective(tag);
        } else {
            tagMapper.updateByPrimaryKeySelective(tag);
        }
    }

    public void deleteById(int tagId) {
        ArticleTag articleTag = new ArticleTag();
        articleTag.setTagId(tagId);
        List<ArticleTag> list = articleTagMapper.getAll(articleTag);
        if (!list.isEmpty()) {
            throw new RTException("该标签已被使用，无法删除！");
        }
        tagMapper.deleteByPrimaryKey(tagId);
    }
}
